import router from './router'
import { useUserStore } from './store/user'
import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css'// Progress 进度条样式
import { getToken } from '@/utils/auth' // 验权

const whiteList = [
    '/login',
    '/forget',
    '/register',
    '/content',
    '/setting/vipcentersilent',
    '/setting/kefu',
    '/setting/pay',
    '/introduce',
    '/invitesilent',
    '/aisilent',
    '/historysilent',
    '/inviteweex',
    '/group'
]
router.beforeEach(async (to, from, next) => {
    NProgress.start()
    if (getToken()) {
        console.log('====getToken')
        if (to.path === '/login') {
            next({ path: '/' })
        } else {
            to.meta.fromPath = from.fullPath
            const store = useUserStore()
            if (store.isLogin) {
                next()
            } else {
                try {
                    // get user info
                    await store.getInfo()
                    next({ ...to, replace: true })
                } catch (error) {
                    console.log(error)
                    // remove token and go to login page to re-login
                    await store.resetToken()
                    next(`/login?redirect=${to.path}`)
                    NProgress.done()
                }
            }
        }
    } else {
        console.log('to.path', to.path);
        // 如果在数组中没找到指定元素则返回 -1
        if (whiteList.indexOf(to.path) !== -1) {
            next()
            NProgress.done()
        } else {
            next('/login')
            NProgress.done()
        }
    }
})

router.afterEach(() => {
    NProgress.done() // 结束Progress
    window.timer = null
})
